package com.easy.controller;

import com.easy.bean.User;
import com.easy.service.IUserService;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    IUserService userService;

    @RequestMapping("getuserinfo")
    @ResponseBody
    public LayData getLoginUser(HttpSession session) {
        User loginuser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        int id = loginuser.getId();
        User user = userService.getUserByID(id);
        return LayData.success(200,"",user);
    }
    @RequestMapping("edit")
    @ResponseBody
    public LayData editUser(HttpSession session, User user) {
        if(user.getId()==0){
            User loginuser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
            int id = loginuser.getId();
            user.setId(id);
        }
        userService.editUser(user);
        return LayData.success(200,null);
    }

    @RequestMapping("getuserbyusername")
    @ResponseBody
    public LayData getUserByUsername(User user) {
        User userData=userService.getUser(user);
        return LayData.success(userData);
    }

    @RequestMapping("register")
    @ResponseBody
    public LayData register(User user,String confirmpassword) {
        boolean check=SYS.check("^\\w{6,16}$",user.getUsername(),user.getPassword(),confirmpassword);
        if(!check){
            return LayData.success(400,"格式不正确");
        }
        User userData=userService.getUser(user);
        if(userData!=null){
            return LayData.success(400,"账号已存在");
        }
        String hexpass=SYS.degest(user.getPassword());
        user.setPassword(hexpass);
        int count =userService.add(user);
        return LayData.success(200,"注册成功",userData);
    }
}
